#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <string>

using namespace std;
#define NUM 10

enum State { OK, EROR };

class threadDate
{
public:
    threadDate(const string& name, State state, uint64_t time)
        : _trname(name)
        , _state(state)
        , _createTime(time)
    {}

public:
    string _trname;
    State _state;
    uint64_t _createTime;
};

void* thread_run(void* argv)
{
    //char* trname = (char*)argv;
    threadDate* td = (threadDate*)argv;
    int cnt = 5;
    while(cnt)
    {
        cout << "new thread is running, my name is " << td->_trname << " createTime: " << td->_createTime << endl;
        cnt--;
        sleep(1);
    }

    // return nullptr;

    // int* a = (int*)argv;
    // *a = 1;
    // pthread_exit(a);

    //pthread_exit((void*)11);

    pthread_exit((void*)td);
}

int main()
{
    pthread_t threads[NUM];

    for(int i = 0; i < NUM; i++)
    {
        //char* trname = new char[64];
        char trname[64]; //因为这块空间是属于主线程的，所以会存在数据覆盖的情况
        snprintf(trname, 64, "thread-%d", i + 1);
        threadDate* td = new threadDate(trname, OK, time(nullptr));
        pthread_create(&threads[i], nullptr, thread_run, td); 
    }

    // while (true)
    // {
    //     cout << "main thread running, new thread id : " << endl;
    //     sleep(1);
    // }
    // sleep(1);
    // for(int i = 0; i < NUM; i++)
    // {
    //     cout << "thread: " << i << ", exit: " << a[i] << endl;
    // }

    void* ret = nullptr;
    for(int i = 0; i < NUM; i++)
    {
        pthread_join(threads[i], &ret);
        //cout << "thread " << i + 1 << " ret->" << (int64_t)ret << endl;
        threadDate* td = static_cast<threadDate*>(ret);
        if(td->_state == OK)
        {
            cout << td->_trname << " createTime: " << td->_createTime << endl;
        }
        delete td;
    }

    // cout << sizeof(a) << endl; 真64位下的指针大小为8字节

    return 0;
}